package com.magicsoft.app.wcf;

import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.boyuan.huijiaoyu.R;
import com.example.app.AppJson;
import com.example.weather.Allcity;
import com.example.weather.FutureWeather;
import com.example.weather.Hotcity;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.magicsoft.app.entity.AccountInfo;
import com.magicsoft.app.entity.EmployeeRightsEntity;
import com.magicsoft.app.entity.RememberEntity;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.TokenHelper;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;

/**
 * 首页请求接口
 * 
 * @author cheng
 * 
 */
public class HomeService extends BaseService {

	public HomeService(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	

	public void getQrcode(String objectType, String id, String action,
			String content, PostRecordResponseListener listener) {
		String getParamString = "";
		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}
		String requestUrl = Constant.QRCODE + getParamString + "&objectType="
				+ objectType + "&id=" + id + "&action=" + action + "&content="
				+ content;
		if (listener != null) {
			listener.onFinish(requestUrl);
		}

	}

	/*
	 * AG端获取个人信息
	 */
	public void getPersonInfo(String username,
			final GetMultilParamsListener listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, true);
		} catch (Exception e) {
		}

		String requestUrl = Constant.ACCOUNT + getParamString;

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				try {
					String code = response.getString("code");
					if ("0".equals(code)) {
						JSONObject content = response.getJSONObject("content");
						Type type = new TypeToken<AccountInfo>() {
						}.getType();
						AccountInfo accountInfo = gson.fromJson(
								content.toString(), type);
						if (listener != null) {
							listener.onFinish(accountInfo);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				super.onSuccess(statusCode, headers, response);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	/*
	 * 修改个人信息
	 */
	public void changePersonInfo(String ChangeInfoJson,
			final PostRecordResponseListener listener) {
		String requestUrl = Constant.ACCOUNT;
		RequestParams params = new RequestParams();

		try {//
			params = TokenHelper.fetchColourTokenChangePersoninfo(context,
					true, ChangeInfoJson);
		} catch (Exception e) {
			Log.e("HomeService", "Exception =" + e.getMessage());
		}

		AsyncHttpServiceHelper.put(requestUrl, params,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								if (listener != null) {
									listener.onFinish(message);
								}
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
						super.onSuccess(statusCode, headers, response);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						Log.e("HomeService changePersonPhone",
								"onFailure responseString=" + responseString);
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						Log.e("HomeService changePersonPhone",
								"onFailure errorResponse="
										+ errorResponse.toString());
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
	}

	/**
	 * 获取用户应用权限
	 */
	public void getEmployeeRight(
			final GetOneRecordListener<List<EmployeeRightsEntity>> listener) {


		RequestParams params = new RequestParams();
		params.put("loginUsername", "mytest");
		params.put("loginPassword", "123456");

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.EMPLOYEE_RIGHTS + getParamString;

		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {

					private List<EmployeeRightsEntity> datas;

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {

							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								JSONArray contentArray = response
										.getJSONArray("content");

								if (contentArray.toString().length() > 5) {
									Log.e("wqwq11", "");
									Type contentType = new TypeToken<List<EmployeeRightsEntity>>() {
									}.getType();
									datas = gson.fromJson(
											contentArray.toString(),
											contentType);

								}

								if (listener != null) {
									listener.onFinish(datas);
								}
							} else {
								if (listener != null)
									listener.onFailed(message);
							}

						} catch (Exception e) {

							if (listener != null)
								listener.onFailed(context.getResources()
										.getString(// JSON
													// 解析错误
												R.string.json_analysis_wrong));
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, responseString,
								throwable);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));
					}
				});

	}

	/**
	 * 获取用户应用权限
	 */
	public void getAuth(final GetOneRecordListener<List<EmployeeRightsEntity>> listener) {

		// RememberEntity rememberEntity = SharePreferenceHelper
		// .GetRememberEntity(context);
		// String username = rememberEntity.getAdmin();
		// String password = rememberEntity.getPsw();

		RequestParams params = new RequestParams();

		params.put("loginUsername", "18030095903");
		params.put("loginPassword", "123456");

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.AUTH + getParamString;

		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {

					private List<EmployeeRightsEntity> datas;

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							String contentEncrypt = response
									.getString("contentEncrypt");
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								// JSONArray contentArray = response
								// .getJSONArray("content");
								// JSONObject contentObject =
								// contentArray.getJSONObject(0);
								// String name =
								// contentObject.getString("name");
								// String type =
								// contentObject.getString("type");
								// String clientCode =
								// contentObject.getString("clientCode");
								// JSONObject url =
								// contentObject.getJSONObject("url");
								// String normal = url.getString("normal");
								// String normalIos = url.getString("ios");
								// String normalAndroid =
								// url.getString("android");
								// JSONObject icon =
								// contentObject.getJSONObject("icon");
								// String iconIos = icon.getString("ios");
								// String iconAndroid =
								// icon.getString("android");
								// Log.i("getAuth1112", response.toString());
								// Type employeeType = new
								// TypeToken<List<AppJson>>() {
								// }.getType();
								// Log.i("getAuth3", "    buxing");
								// List<AppJson> employeeResps = gson
								// .fromJson(contentArray.toString(),
								// employeeType);
								// Log.i("getAuth5", "");
								JSONArray contentArray = response
										.getJSONArray("content");

								// Log.e("wqwq00",
								// ""+contentArray.toString().length());
								// if (contentArray.toString().length() > 5) {
								Type contentType = new TypeToken<List<EmployeeRightsEntity>>() {
								}.getType();
								datas = gson.fromJson(contentArray.toString(),
										contentType);

								// }

								if (listener != null) {
									listener.onFinish(datas);
								}
							} else {
								if (listener != null)
									listener.onFailed(message);
							}

						} catch (Exception e) {

							if (listener != null)
								listener.onFailed(context.getResources()
										.getString(// JSON
													// 解析错误
												R.string.json_analysis_wrong));
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, responseString,
								throwable);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						// TODO Auto-generated method stub
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));
					}
				});

	}

	/*
	 * 百度天气请求
	 */
	public void getWeatherList(String city,
			final GetOneRecordListener<List<FutureWeather>> listener) {
		String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location="
				+ city + "+&output=json&ak=KsSPzG8Y72VhGUXhc0iGgCDm";
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					JSONArray results = response.getJSONArray("results");
					JSONObject jsonObject = results.getJSONObject(0);
					String pm = jsonObject.getString("pm25");
					SharePreferenceHelper.setWeatherPm(pm, context);
					JSONArray weather_data = jsonObject
							.getJSONArray("weather_data");
					Type type = new TypeToken<List<FutureWeather>>() {
					}.getType();

					List<FutureWeather> FutureWeatherlist = gson.fromJson(
							weather_data.toString(), type);
					if (listener != null) {
						listener.onFinish(FutureWeatherlist);
					}

				} catch (JSONException e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
								// 解析错误
								R.string.json_analysis_wrong));
					String message = e.getMessage();

					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});

	}

	public void getHotcitylist(
			final GetOneRecordListener<List<Hotcity>> listener) {

		// String getParamString = "";
		String requestUrl = "http://7xiroe.com1.z0.glb.clouddn.com/cities.txt";
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					JSONArray hotcity = response.getJSONArray("hotcity");
					Log.e("HomeService", "hotcity =" + hotcity.toString());
					Type type = new TypeToken<List<Hotcity>>() {
					}.getType();
					List<Hotcity> Hotcitylist = gson.fromJson(
							hotcity.toString(), type);
					if (listener != null) {
						listener.onFinish(Hotcitylist);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	/*
	 * 请求城市列表
	 */
	public void getAllCitylist(
			final GetOneRecordListener<List<Allcity>> listener) {

		// String getParamString = "";
		String requestUrl = "http://7xiroe.com1.z0.glb.clouddn.com/cities.txt";
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					JSONArray allcity = response.getJSONArray("allcity");
					Log.e("HomeService", "allcity =" + allcity.toString());

					Type type = new TypeToken<List<Allcity>>() {
					}.getType();
					List<Allcity> Allcitylist = gson.fromJson(
							allcity.toString(), type);
					if (listener != null) {
						listener.onFinish(Allcitylist);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

}
